import 'package:aidou/controller/videoListController.dart';
import 'package:aidou/http/repository/home.respository.dart';
import 'package:aidou/model/video.dart';
import 'package:aidou/widgets/video/buttonColumn.dart';
import 'package:aidou/widgets/video/comment.dart';
import 'package:aidou/widgets/video/player.dart';
import 'package:flutter/material.dart';
import 'package:safemap/safemap.dart';
import 'package:video_player/video_player.dart';

class VideoPlayerPage extends StatefulWidget {
  final String value;
  final VideoListController videoController;
  const VideoPlayerPage({
    Key? key,
    required this.value,
    required this.videoController,
  }) : super(key: key);

  @override
  _VideoPlayerPageState createState() => _VideoPlayerPageState();
}

class _VideoPlayerPageState extends State<VideoPlayerPage>
    with AutomaticKeepAliveClientMixin {
  PageController _pageController = PageController();
  Map<int, bool> favoriteMap = {};
  bool videoTapOnPause = false;
  int pageIndex = 1;

  @override
  void initState() {
    this.initData();
    super.initState();
  }

  /// 初始化数据
  void initData() async {
    // 第一页视频数据
    var videoList = await this.getWorkList();
    widget.videoController.init(
        pageController: _pageController,
        initialList: videoList
            .map(
              (e) => VPVideoController(
                videoInfo: e,
                builder: () => VideoPlayerController.network(e.pathUrl),
              ),
            )
            .toList(),
        videoProvider: (int index, List<VPVideoController> list) async {
          print('index===============${index}');
          var list = await this.getWorkList();
          return list
              .map((e) => VPVideoController(
                    videoInfo: e,
                    builder: () => VideoPlayerController.network(e.pathUrl),
                  ))
              .toList();
        });
    widget.videoController.addListener(() {
      if (mounted) {
        setState(() {});
      }
    });
  }

  /// 获取作品列表数据
  Future<List<VideoData>> getWorkList() async {
    List<VideoData> list = await HomeRepository.getVideoList(
        pageIndex: pageIndex, pageSize: 10, type: 1);
    setState(() {
      pageIndex = pageIndex + 1;
    });
    List<VideoData> data = await this.loopGetPlayUrl(list);
    return data;
  }

  Future<List<VideoData>> loopGetPlayUrl(List<VideoData> data) async {
    List<VideoData> d = data;
    List<String> urlList =
        await Future.wait<String>(data.map((e) => this.getPlayUrl(e)));
    for (var i = 0; i < d.length; i++) {
      d[i].pathUrl = urlList[i];
    }
    print('urlList=====${urlList}');
    return d;
  }

  /// 获取第三方视频播放地址
  Future<String> getPlayUrl(VideoData item) async {
    String url = '';
    if (item.source == 2) {
      String res = await HomeRepository.getPlayUrl(businessId: item.id);
      url = res;
    } else {
      url = item.pathUrl;
    }
    return url;
  }

  @override
  Widget build(BuildContext context) {
    double a = MediaQuery.of(context).size.aspectRatio;
    bool hasBottomPadding = a < 0.55;
    return PageView.builder(
      key: Key(widget.value),
      controller: _pageController,
      itemCount: widget.videoController.VideoCount,
      scrollDirection: Axis.vertical,
      itemBuilder: (context, i) {
        // 记录点赞
        bool isF = SafeMap(favoriteMap)[i].boolean;
        var player = widget.videoController.playerOfIndex(i)!;
        var data = player.videoInfo!;
        // 右侧按钮
        Widget buttons = VideoButtonColumn(
          isFavorite: isF,
          onAvatar: () {},
          // 点赞
          onFavorite: () {
            setState(() {
              favoriteMap[i] = !isF;
            });
          },
          // 评论
          onComment: () {
            showModalBottomSheet(
              backgroundColor: Colors.white.withOpacity(0),
              context: context,
              builder: (BuildContext context) => VideoCommentBottomSheet(),
            );
          },
          // 分享
          onShare: () {
            print('share');
          },
        );

        // video
        Widget currentVideo = Center(
          child: AspectRatio(
            // 按照比例缩放
            aspectRatio: player.controller.value.aspectRatio,
            child: VideoPlayer(player.controller),
          ),
        );

        return player.initialized
            ? VideoPlayerItem(
                // 手势播放与自然播放都会产生暂停按钮状态变化，待处理
                hidePauseIcon: player.showPauseIcon.value && videoTapOnPause,
                aspectRatio: 9 / 16.0,
                key: Key(data.pathUrl + '$i'),
                tag: data.pathUrl,
                bottomPadding: 16.0,
                userInfoWidget: VideoInfo(
                  title: data.title,
                  nickName: data.nickName,
                  bottomPadding: hasBottomPadding ? 16.0 : 16.0,
                ),
                onSingleTap: () async {
                  if (player.controller.value.isPlaying) {
                    setState(() {
                      videoTapOnPause = true;
                    });
                    await player.pause();
                  } else {
                    setState(() {
                      videoTapOnPause = false;
                    });
                    await player.play();
                  }
                },
                rightButtonColumn: buttons,
                video: currentVideo,
              )
            : Container(
                width: double.infinity,
                height: double.infinity,
                color: Colors.amber,
              );
      },
      // 切屏事件
      onPageChanged: (int index) {
        setState(() {
          // 滑屏后将暂停图标的状态恢复
          videoTapOnPause = false;
        });
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  didUpdateWidget(oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  bool get wantKeepAlive => true;
}
